package com.hsjk.szwj.module.pay.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsjk.szwj.framework.common.constant.RedisKeyConstant;
import com.hsjk.szwj.module.pay.dal.dataobject.system.PayInterfaceDefineDO;
import com.hsjk.szwj.module.pay.dal.mysql.IPayInterfaceDefineMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/21 17:38
 **/
@Service
public class PayInterfaceDefineService
        extends ServiceImpl<IPayInterfaceDefineMapper, PayInterfaceDefineDO> {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public List<PayInterfaceDefineDO> list(LambdaQueryWrapper<PayInterfaceDefineDO> wrapper) {
        return list(wrapper);
    }

    public Long getIdByCode(String code) {
        String key = RedisKeyConstant.PAY_INTERFACE_DEFINE_CODE_KEY + code;
        String ifIdStr = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(ifIdStr)) {
            return Long.valueOf(ifIdStr);
        } else {
            PayInterfaceDefineDO one = getOne(new LambdaQueryWrapper<PayInterfaceDefineDO>()
                    .eq(PayInterfaceDefineDO::getIfCode, code));
            if (one != null) {
                stringRedisTemplate.opsForValue().set(key, String.valueOf(one.getId()));
                return one.getId();
            }
        }
        return null;
    }

    public String getCodeById(Long id) {
        String key = RedisKeyConstant.PAY_INTERFACE_DEFINE_CODE_KEY + id;
        String ifCodeStr = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(ifCodeStr)) {
            return ifCodeStr;
        } else {
            PayInterfaceDefineDO one = getOne(new LambdaQueryWrapper<PayInterfaceDefineDO>()
                    .eq(PayInterfaceDefineDO::getId, id));
            if (one != null) {
                stringRedisTemplate.opsForValue().set(key, one.getIfCode());
                return one.getIfCode();
            }
        }
        return null;
    }

    public PayInterfaceDefineDO getOne(LambdaQueryWrapper<PayInterfaceDefineDO> wrapper, boolean throwEx) {
        return getOne(wrapper);
    }

}
